using System.Collections;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Serialization;
using Awaiter;
using Minions.Classes;
using Nsb.Classes;
using jQueryApi;

namespace MinionsEdit.Classes
{
    [IgnoreNamespace]
    public class MiCanvasEdit : MinionEdit
    {
        protected string LastSaved;

        #region Finders

        #endregion Finders

        #region Evokes

        public override void SaveAw(Evo evo) // Value = (bool)noUndo
        {
            Await awp = evo.TakeAndOwnResponse();
            Debug.Assert(awp != null, "SaveAw awp != null");
            Debug.Assert(PartitionKey != null && RowKey != null, "MiCanvasEdit.SaveAw PartionKey & RowKey not null");
            bool noUndo = (bool) evo.Value;
            new Await()
                .AddDx(
                    delegate
                    {
                        string content = "[" + Json.Stringify(LiveCanvasData, delegate(string n, object o) { return o; }, 4) + "]";
                        if (content != LastSaved)
                        {
                            if (!noUndo)
                            {
                                Undo.Save(new UndoItem(content), PartitionKey);
                                Evo.Trigger(EvoEvents.RedrawPageGear);
                            }
                            LastSaved = content;
                            Evo.TriggerAw(awp, Evo.StoreBlobAw, new Dictionary("partitionKey", PartitionKey, "rowKey", RowKey, "content", content, "backup", true));
                            Evo.Trigger(EvoEvents.OnPageSave);
                        }
                        else
                        {
                            // ReSharper disable PossibleNullReferenceException
                            awp.Done();
                            // ReSharper restore PossibleNullReferenceException
                        }
                    }
                )
                .AddDx(delegate { Evo.Trigger(EvoEvents.SetPageHeight); })
                .Commit();
        }

        #endregion Evokes

        #region Events

        public static void FlashWindowEv(jQueryEvent e)
        {
            FlashWindow();
        }

        #endregion Events

        #region Methods

        public MiCanvasData LiveCanvasData
        {
            get
            {
                TheCanvas.CanvasData.minion = LiveData;
                return TheCanvas.CanvasData;
            }
        }

        public override Minion NewMinion(Minion top)
        {
            return new MiCanvasEdit().SetTop(top);
        }

        #endregion Methods
    }
}